package com.gdth.bank;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import com.gdth.bank.activity.LoginActivity;
import com.gdth.bank.presenter.SplashPresenter;
import com.gdth.bank.utils.AntiHijackingUtil;
import com.gdth.bank.utils.AppUtil;
import com.gdth.bank.utils.LogUtils;
import com.gdth.bank.view.SplashView;
import com.gdth.database.bean.SplashGetImageBean;
import com.gdth.http.method.EngDNS;
import com.gdth.http.method.httpsUtils;
import com.gdth.resource.Constant;
import com.gdth.service.HeartService;
import com.gdth.service.KeepLiveJobService;
import com.gdth.service.LogService;
import com.gdth.utils.RootUtil;
import com.gdth.utils.ToolUtil;
import com.gdth.utils.webViewUtils;
import com.gdth.widget.dialog.BaseToast;
import com.google.gson.Gson;
import com.tbruyelle.rxpermissions2.RxPermissions;


import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 启动页面
 * @author arvin
 *
 */
public class SplashScreenActivity extends FragmentActivity implements SplashView {
	
	private SplashPresenter mSplashPresenter;
	private TextView tishi;
	public ImageView mImageView;
	/**
	 * 启动界面挑战时间
	 */
	public int DelayedTime = 100, BootTime = 2000;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.system_splash);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,    
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
		if(RootUtil.isDeviceRooted()) {
			//Toast.makeText(SplashScreenActivity.this, "本应用不支持在root手机上面使用", Toast.LENGTH_LONG).show();
			showDialog("本应用不支持在root手机上面使用");
			postDelayedexit();
			return ;
		}
		initView();
		mSplashPresenter = new SplashPresenter(this);
		initService();
		RxPermissions rxPermissions = new RxPermissions(SplashScreenActivity.this);
		rxPermissions.requestEachCombined(Manifest.permission.READ_EXTERNAL_STORAGE,
				Manifest.permission.WRITE_EXTERNAL_STORAGE,
				Manifest.permission.CAMERA,
				Manifest.permission.RECORD_AUDIO,
				Manifest.permission.ACCESS_COARSE_LOCATION,
				Manifest.permission.READ_PHONE_STATE,
				Manifest.permission.ACCESS_FINE_LOCATION,
				Manifest.permission.READ_CONTACTS).subscribe(permission -> {
					if(permission.granted){
						initData();
					}else if(permission.shouldShowRequestPermissionRationale){
						BaseToast.getInstance().ShowSystemToast(SplashScreenActivity.this,"未授权将会影响正常使用，请您在设置中开启相关权限");
					}else{
						initData();
					}
				} );
//		if (Build.VERSION.SDK_INT >= 23) {   // 6.0 以前要去动态获取权限
//			if(PermissionUtil.checkPermissionFile(this)) {
//				// 没有权限的时候去申请权限
//			}else {		// 有权限了
//				initData();
//			}
//		}else {
//			initData();
//		}
	}

	public void exit(){
		//android进程完美退出方法。
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

		//让Activity的生命周期进入后台，否则在某些手机上即使sendSignal 3和9了，还是由于Activity的生命周期导致进程退出不了。除非调用了Activity.finish()
		this.startActivity(intent);

		android.os.Process.killProcess(android.os.Process.myPid());
		//System.runFinalizersOnExit(true);
		System.exit(0);
	}

	private AlertDialog builder;

	/**
	 * 提示
	 */
	private void showDialog(String content) {

		builder = new AlertDialog.Builder(this).create();
		builder.setTitle("安全提示");
		builder.setMessage(content);
		builder.setButton(DialogInterface.BUTTON_POSITIVE,"确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();//关闭对话框
			}
		});
		builder.show();

	}

	/**
	 * 延时退出
	 * @param
	 * @param
	 */
	public void postDelayedexit(){
		try{
			new Handler().postDelayed(new Runnable() {
				public void run() {
					if(builder.isShowing()) {
						builder.dismiss();
					}
					exit();
				}
			}, 3000);
		}
		catch(Exception e){
			//Log.w("", e.getMessage());
		}
	}
	
	private void initView() {
		mImageView = (ImageView) findViewById(R.id.splash_img);
		tishi =(TextView) findViewById(R.id.tishi);
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		isBack = false;
	}
	
	@TargetApi(23)
	@Override
	public void onRequestPermissionsResult(int requestCode,  String[] permissions,int[] grantResults) {
	    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
	    
	    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
	        //TODO:已授权
	    	
	     	initData();
	    } else {
	       //TODO:用户拒绝
	    	Toast.makeText(SplashScreenActivity.this, "未授权将会影响正常使用", Toast.LENGTH_SHORT);
	    	
	    }
	   

	}
    /**
     * 启动双服务
     * xjc --- 2018.5.17 : 去掉两个常驻服务保活， 改为，5.0 之前用一个定时钟时钟时常让一个server 保活， 5.0 之后用jobserver保活
     */
    private void initService(){
//    	boolean isStart = AppUtil.isServiceWorked(this, "com.gdth.service.BankService");
//		if(!isStart) {
//			this.startService(new Intent(this, BankService.class));
//		}
    	boolean isStart;
    	if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    		isStart = AppUtil.isServiceWorked(this, "com.gdth.service.HeartService");
    		if(!isStart) {
    			this.startService(new Intent(this, HeartService.class)); 
    		}
    	}else {
    		isStart = AppUtil.isServiceWorked(this, "com.gdth.service.KeepLiveJobService");
    		if(!isStart) {
//    			KeepLiveJobService ser = new KeepLiveJobService(); 
//        		ser.startSever();
    			startSever();
    		}
    	}
    	isStart = AppUtil.isServiceWorked(this, "com.gdth.service.LogService");
		if(!isStart) {
			this.startService(new Intent (this, LogService.class));
		}
    }
    
    /**
	 * 延时加载
	 * @param
	 * @param
	 */
	public void postDelayed(){
		try{
			new Handler().postDelayed(new Runnable() {
	            public void run() {
	            	activityTO();
	            }
	        }, BootTime);
		}
		catch(Exception e){
			//Log.w("", e.getMessage());
		}
	}
	
	private void initData() {
		postDelayed();
//		 boolean isAvailable=isNetworkConnected(this);
//	       if(isAvailable){
//	    		//mSplashPresenter.getAppImage();
//	    		getImage();
//	       }else{
//	    	   postDelayed();
//	       }
	}
	
	
	 public boolean isNetworkConnected(Context context) {  
	      if (context != null) {  
	          ConnectivityManager mConnectivityManager = (ConnectivityManager) context  
	                  .getSystemService(Context.CONNECTIVITY_SERVICE);  
	         NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();  
	          if (mNetworkInfo != null) {  
	              return mNetworkInfo.isAvailable();  
	          }  
	      }  
	     return false;  
	 }  
	
	@SuppressLint("NewApi")
	public void startSever() {
		@SuppressLint("WrongConstant")
		JobScheduler scheduler =  (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
		ComponentName componentName =  new ComponentName(BankApplication.mInstance.getBaseContext(), KeepLiveJobService.class);
		JobInfo.Builder builder =new  JobInfo.Builder(1, componentName);
        if (Build.VERSION.SDK_INT >= 24) {
            builder.setMinimumLatency(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS); //执行的最小延迟时间
            builder.setOverrideDeadline(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS);  //执行的最长延时时间
            builder.setMinimumLatency(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS);
            builder.setBackoffCriteria(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS, JobInfo.BACKOFF_POLICY_LINEAR);//线性重试方案
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                builder.setPeriodic(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS);
            }
        }
        builder.setPersisted(true);  // 设置设备重启时，执行该任务
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
        builder.setRequiresCharging(true); // 当插入充电器，执行该任务
        JobInfo  info = builder.build();
        scheduler.schedule(info); //开始定时执行该系统任务
	}

	@Override
	public void showProgressDialog(String msg) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void hideProgressDialog() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void showMessage(String msg) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void getAppImage(String param) { // 获取照片
		// TODO Auto-generated method stub
		SharedPreferences preferences = getSharedPreferences("splashImage", MODE_PRIVATE);
        String LocalParam = preferences.getString("ImageUrl", "");// 获取本地存储数据
        LogUtils.i("________________" , "________________" + param);
       if(LocalParam.equals(param)) {		  // 如果数据相同
    	   try {
    		   SplashGetImageBean getImage = new SplashGetImageBean();
    	       Gson mGson = new Gson();
    	       getImage = mGson.fromJson(param, getImage.getClass());
    	       number = getImage.getViewpager().size(); 
    	       // 遍历所有文件是否存在 // 如果存在， 就等2秒跳转， 如果不存在， 就进行下载
    	       isFileExists(getImage,getImage.getLogin_image(),ToolUtil.LoginBackGround); // 检查文件是否存在
    	   }catch(NullPointerException e) {
    		   postDelayed();
    	   }
		  
       }else {		// 如果数据不同
    	   try {
	    	   isDownLoad = true;
	    	   Editor editor = preferences.edit();
	           editor.putString("ImageUrl", param);
	           editor.commit();
	           SplashGetImageBean getImage = new SplashGetImageBean();
		       Gson mGson = new Gson();
		       getImage = mGson.fromJson(param, getImage.getClass());
		       number = getImage.getViewpager().size(); 
		       DownFile(getImage,getImage.getLogin_image(),ToolUtil.LoginBackGround);
    	   }catch(NullPointerException e) {
    		   activityTO();
    	   }
       }
	}
	private static final int DEFAULT_TIMEOUT = 3;
	private int number = 0;
	private boolean isDownLoad = false;
	  /**
     * 手动创建一个OkHttpClient并设置超时时间
     * @return
     */
    private OkHttpClient getOkHttpClient(){

    	OkHttpClient client = new OkHttpClient.Builder()
    		.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
//    		.connectTimeout(1000, TimeUnit.MINUTES)
		    .readTimeout(1000, TimeUnit.MINUTES)
		    .writeTimeout(3000, TimeUnit.MINUTES)
			.dns(new EngDNS())
    		.sslSocketFactory(httpsUtils.getSSLSocketFactory())
    		.hostnameVerifier(httpsUtils.getHostnameVerifier())
    		.build();
    	
    	return client;
    }
    
    public void isFileExists(final SplashGetImageBean getImage , String url ,  final String IamgeName) {
    	LogUtils.i("________________" , "________________" + number);
    	 File file = new File(ToolUtil.getImagePath(IamgeName));
    	   if(file.exists()) { // 文件存在 
    		   if(number == 0) {
    			   activityTO();
    		   }else {
    			   if(number != 0) {
	        			number--;
    			   }
    			   isFileExists(getImage,getImage.getViewpager().get(number),"viwepager" + number + ".jpg");
    			 return ;
    		   }
    	   }else {		// 文件不存在
    		   DownFile(getImage,url,IamgeName);		// 下载文件
    	   }
    }
    
	
	public void DownFile(final SplashGetImageBean getImage , final String url ,  final String IamgeName) {
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				tishi.setVisibility(View.VISIBLE);
				tishi.setText("数据初始化中" + ((4-number)*24 +1) + "%" );
			}
		});
		

		OkHttpClient okHttpClient= getOkHttpClient();
		  Request request=new Request.Builder()
		        .get()
		        .url(Constant.image_url_param + url)
		        .addHeader("attestation", webViewUtils.getHeadParam())
		        .addHeader("USER-AGENT", "okhttp viewAction")
		        .build();
		  Call call=okHttpClient.newCall(request);
		  call.enqueue(new Callback() {
		     

			@Override
			public void onFailure(Call arg0, IOException arg1) {
				// TODO Auto-generated method stub
				 LogUtils.i("________________" , arg1.toString());
				 activityTO(); 
			}

			@Override
			public void onResponse(Call arg0, Response response) throws IOException {
				// TODO Auto-generated method stub
				//将响应数据转化为输入流数据
				//String path = ToolUtil.getImagePath(IamgeName);
				if(!response.isSuccessful() && number == 0) {
					activityTO(); 
				}
				String path = ToolUtil.getImagePath(IamgeName) ;
				InputStream is = null;
		        byte[] buf = new byte[2048];
		        int len = 0;
		        FileOutputStream fos = null;
		        try {
		            is = response.body().byteStream();
		            File file = new File(path);
		            fos = new FileOutputStream(file);
		            while ((len = is.read(buf)) != -1) {
		                fos.write(buf, 0, len);
		            }
		            fos.flush();
		        } catch (Exception e) {
		           
		        } finally {
		            try {
		                if (is != null)
		                    is.close();
		            } catch (IOException e) {
		            	
		            }
		            try {
		                if (fos != null)
		                    fos.close();
		            } catch (IOException e) {
		            	
		            }
		        }
		       
		          LogUtils.i("________________" , IamgeName);
		          if(isDownLoad) {
		        	  if(number > 0) {
		        		  number--;
		        		  DownFile(getImage,getImage.getViewpager().get(number),"viwepager" + number + ".jpg");
		        	 }else {
		        		 if(number == 0) {
		        			 activityTO();
		        		 }
		        	 }
		          }else {
		        	  isFileExists(getImage,url,IamgeName);
		          }
			}
		  });
	} 
	
	 
	public void getImage() {
		OkHttpClient okHttpClient= getOkHttpClient();
		  Request request=new Request.Builder()
		        .get()
		        .url(Constant.url + "bank/appimg!getImgs.do" )
		        .addHeader("attestation", webViewUtils.getHeadParam())
		        .addHeader("USER-AGENT","okhttp viewAction")
		        .build();
		  Call call=okHttpClient.newCall(request);
		  call.enqueue(new Callback() {
		     

			@Override
			public void onFailure(Call arg0, IOException arg1) {
				// TODO Auto-generated method stub
				postDelayed();
				 LogUtils.i("________________" , arg1.toString());
			}

			@Override
			public void onResponse(Call arg0, Response response) throws IOException {
				// TODO Auto-generated method stub
				//将响应数据转化为输入流数据
				if(response.isSuccessful()) {
					String param = response.body().string();
					getAppImage(param);
				}else {
					postDelayed();
				}
				
			}
		  });
	} 
	
	public void activityTO(){
		Intent intent=new Intent(SplashScreenActivity.this, LoginActivity.class);
    	startActivity(intent);
    	finish();
	}
	boolean isBack = false;
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		isBack = true;
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		new Thread(new Runnable() {
            @Override
            public void run() {
                // 白名单
                boolean safe = AntiHijackingUtil.checkActivity(getApplicationContext());
                // 系统桌面
                boolean isHome = AntiHijackingUtil.isHome(getApplicationContext());
                // 锁屏操作
                boolean isReflectScreen = AntiHijackingUtil.isReflectScreen(getApplicationContext());
                // 判断程序是否当前显示
                if (!safe && !isHome && !isReflectScreen && !isBack) {
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), R.string.activity_safe_warning,
                            Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }
        }).start();
		
	}
}
